<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮（新增...） -->
      <template #toolbar>
        <div v-for="(item, index) in butData" :key="index">
          <a-popconfirm
            v-if="item.btnKey === 'btnClose'"
            title="是否确认行关闭？"
            ok-text="是"
            cancel-text="否"
            placement="bottom"
            @confirm="handleRowClose()"
          >
            <a-button :key="index" :type="item.btnType" v-auth="item.auth" v-show="item.ifShow">
              <Icon :icon="item.icon" /> {{ t(item.title) }}
            </a-button>
          </a-popconfirm>
          <a-button
            v-else
            :key="index"
            :type="item.color"
            @click="item.do"
            v-auth="item.auth"
            v-show="item.ifShow"
          >
            <Icon :icon="item.icon" /> {{ t(item.title) }}
          </a-button>
        </div>
      </template>
      <!-- 表格插槽 -->
      <!-- <template #firstColumn="{ record }">
        <a @click="handleForm({ cusCode: record.cusCode, invCode: record.invCode })">
          {{ record.cusCode }}
        </a>
      </template> -->
    </BasicTable>
    <!-- 页签方式编辑 -->
    <InputFormTabs @register="registerDrawer2" @success="handleSuccess" />
    <!--拆分行-->
    <InputFormTabsSplitRow @register="registerDrawer3" @success="handleSuccess1" />
    <!--新增行-->
    <InputFormTabsNew @register="registerDrawer4" @success="handleSuccess" />
    <!--初始行-->
    <InputFormTabsInit @register="registerDrawer5" @success="handleSuccess" />
    <!-- 指定仓库 -->
    <BasicModal v-bind="$attrs" @register="registerModal" title="仓库选择" @ok="handleModal">
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopOrderSaleList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { customListData, listSet } from '/@/api/test/testData';
  import { schemasData, tabConfigData } from '/@/utils/custom';
  import { BasicTable, BasicColumn, useTable, ActionItem } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps, BasicForm, useForm } from '/@/components/Form';
  import InputFormTabs from './formTabs.vue';
  import InputFormTabsSplitRow from './formTabs-splitRow.vue';
  import InputFormTabsNew from './formTabs-new.vue';
  import InputFormTabsInit from './formTabs-init.vue';
  import { updateStash, deleteRow, rowClose } from '/@/api/shop/order/soRds';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { basWarehousetreeData } from '/@/api/bas/house/basWarehouse';

  const { t } = useI18n('shop.order.sale');
  const { showMessage } = useMessage();
  const emit = defineEmits(['success']);
  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    schemas: [],
  });
  const props = defineProps({
    soCode: { type: String, default: '' },
    orderStatus: { type: String, default: '' },
    data: { type: Object, default: {} },
  });

  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });

  let title = ref('');
  const actionColumn: BasicColumn = {
    width: 100,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑行'),
        onClick: handleForm.bind(this, {
          id: record.id,
          rowType: record.rowType,
          cusCode: props.data.cusCode,
          croute: props.data.croute,
          cbustype: props.data.cbustype,
        }),
        auth: 'shop:order:soRds:edit',
        ifShow: props.orderStatus === '4',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除'),
        popConfirm: {
          title: t('是否确认删除？'),
          confirm: handleDelete.bind(this, { id: record.id }),
        },
        auth: 'shop:order:soRds:edit',
        ifShow: props.orderStatus === '4' && record.rowType != '0',
      },
    ],
  };
  onMounted(async () => {
    setTimeout(async () => {
      const res = await listSet({ viewCode: 'shop_order_rds_list001' });
      title.value = res.layVoucherView.name;
      layVoucherView.value = res.layVoucherView;

      searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

      tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

      butData.value = layVoucherView.value.headBtns; //表格右上角按钮
      butData.value.forEach((item) => {
        if (item.btnKey == 'btnAdd') {
          item.do = () =>
            handleAdd({
              soCode: props.soCode,
              cusCode: props.data.cusCode,
              croute: props.data.croute,
              cbustype: props.data.cbustype,
              ope: '1',
            });
          item.ifShow = props.orderStatus === '4';
        }
        // 指定仓库
        if (item.btnKey == 'btnCk') {
          item.do = () => handleCk();
          item.ifShow = props.orderStatus === '4';
        }
        // 拆行
        if (item.btnKey == 'btnChai') {
          item.do = () => handleSplitRow();
          item.ifShow = props.orderStatus === '4';
        }
        // 行关闭
        if (item.btnKey == 'btnClose') {
          item.do = () => handleRowClose();
          item.ifShow = props.orderStatus === '4';
        }
      });

      actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

      listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
      setProps({
        api: customListData,
        beforeFetch: (params) => {
          params.url = listTabConfig.value.api;
          params.soCode = props.soCode;
          return params;
        },
        autoCreateKey: listTabConfig.value.autoCreateKey,
        bordered: listTabConfig.value.bordered,
        // canResize: listTabConfig.value.canResize,
        clearSelectOnPageChange: listTabConfig.value.clearSelectOnPageChange,
        clickToRowSelect: listTabConfig.value.clickToRowSelect,
        ellipsis: listTabConfig.value.ellipsis,
        emptyDataIsShowTable: listTabConfig.value.emptyDataIsShowTable,
        inset: listTabConfig.value.inset,
        isTreeTable: listTabConfig.value.isTreeTable,
        pagination: listTabConfig.value.pagination,
        showIndexColumn: listTabConfig.value.showIndexColumn,
        // showSummary: listTabConfig.value.showSummary,
        showTableSetting: listTabConfig.value.showTableSetting,
        striped: listTabConfig.value.striped,
        useSearchForm: listTabConfig.value.useSearchForm,
        tableSetting: listTabConfig.value.tableSetting,
        titleHelpMessage: listTabConfig.value.titleHelpMessage,
        maxHeight: listTabConfig.value.maxHeight,

        // maxHeight: listTabConfig.value.maxHeight,
        resizeHeightOffset: listTabConfig.value.resizeHeightOffset,
      });
      if (!listTabConfig.value.immediate) {
        reload();
      }
    }, 500);
  });

  const [registerDrawer2, { openDrawer: openDrawer2 }] = useDrawer();
  const [registerDrawer3, { openDrawer: openDrawer3 }] = useDrawer();
  const [registerDrawer4, { openDrawer: openDrawer4 }] = useDrawer();
  const [registerDrawer5, { openDrawer: openDrawer5 }] = useDrawer();
  const [registerTable, { reload, getForm, setProps, getSelectRows }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
      fixed: 'left',
    },
    // maxHeight: 100,
    showSummary: true,
    summaryFunc: handleSummary,
    // scroll: { y: 200 },
  });

  const [registerModal, { openModal, closeModal }] = useModal();
  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 80,
    schemas: [
      {
        label: t('仓库'),
        field: 'whcode',
        fieldLabel: 'whname',
        component: 'TreeSelect',
        componentProps: {
          api: basWarehousetreeData,
          params: { isAll: false, saBusType: props.data.cbustype },
          canSelectParent: false,
          allowClear: true,
        },
        required: true,
        colProps: { lg: 24, md: 24 },
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });

  function handleSummary(tableData: Recordable[]) {
    const totalIquantity = tableData.reduce((prev, next) => {
      prev += next.iquantity ? next.iquantity : 0;
      return prev;
    }, 0);

    const totalInum = tableData.reduce((prev, next) => {
      prev += next.inum ? next.inum : 0;
      return prev;
    }, 0);

    const totalIsum = tableData.reduce((prev, next) => {
      prev += next.isum ? next.isum : 0;
      return prev;
    }, 0);

    const totalCbdefine1 = tableData.reduce((prev, next) => {
      prev += next.cbdefine1 ? next.cbdefine1 : 0;
      return prev;
    }, 0);
    const totalCbdefine2 = tableData.reduce((prev, next) => {
      prev += next.cbdefine2 ? next.cbdefine2 : 0;
      return prev;
    }, 0);

    const totalCbdefine5 = tableData.reduce((prev, next) => {
      prev += next.cbdefine5 ? next.cbdefine5 : 0;
      return prev;
    }, 0);

    const totalIdiscount = tableData.reduce((prev, next) => {
      prev += next.idiscount ? next.idiscount : 0;
      return prev;
    }, 0);

    return [
      {
        _row: '合计',
        // _index: '平均值',
        inum: totalInum,
        iquantity: totalIquantity,
        isum: totalIsum,
        cbdefine1: totalCbdefine1,
        cbdefine2: totalCbdefine2,
        cbdefine5: totalCbdefine5,
        idiscount: totalIdiscount,
      },
    ];
  }
  function handleForm(record: Recordable) {
    //0、初始行  1、新增行  2、初始行
    if (record.rowType === '0') {
      openDrawer5(true, record);
    } else if (record.rowType === '1') {
      // 新增行
      openDrawer4(true, record);
    } else if (record.rowType === '2') {
      // 拆分行
      record.ope = '0';
      openDrawer3(true, record);
    }
  }

  // 新增行
  function handleAdd(record: Recordable) {
    openDrawer4(true, record);
  }

  async function handleDelete(record: Recordable) {
    const res = await deleteRow(record);
    showMessage(res.message);
    handleSuccess();
  }

  /** 指定仓库 */
  async function handleWareHouseSelect(values: Recordable[]) {
    const params = {
      selIds: getSelectRows()
        .map((item) => item.id)
        .join(','),
      bodyVO: {
        cdefine22: values[0].whcode,
      },
    };
    const res = await updateStash(params);
    showMessage(res.message);
    reload();
  }

  // 指定仓库
  async function handleCk() {
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    }
    await openModal(true, {});
    resetFields();
  }

  // 拆行
  async function handleSplitRow() {
    if (!getSelectRows().length) {
      showMessage('请选择一行数据！！');
      return;
    }
    openDrawer3(true, { id: getSelectRows()[0].id, cbustype: props.data.cbustype, ope: '1' });
  }

  // 删行
  async function handleDeleteRow() {
    if (getSelectRows().length) {
      const res = await deleteRow({ id: getSelectRows()[0].id });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
  }

  // 行关闭
  async function handleRowClose() {
    if (getSelectRows().length) {
      var selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      const res = await rowClose({ selIds: selIds.value, soCode: props.soCode });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
  }

  // 指定仓库保存
  async function handleModal() {
    let data = await validate();
    console.log(data);
    const params = {
      selIds: getSelectRows()
        .map((item) => item.id)
        .join(','),
      bodyVO: {
        cdefine22: data.whcode,
      },
    };
    const res = await updateStash(params);
    showMessage(res.message);
    closeModal();
    reload();
  }

  function handleSuccess() {
    emit('success', '');
    reload();
  }

  function handleSuccess1() {
    reload();
  }
</script>
<style scoped>
  .jeesite-editable-cell__action {
    display: none;
  }
  /deep/ .jeesite-basic-table .ant-table-content {
    min-height: 50px;
  }

  .edit-cell-align-center {
    width: 100% !important;
  }
</style>
